package yams.resource.impl;

import com.google.common.collect.Maps;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import yams.domain.*;
import yams.resource.IHouseResource;
import yams.resource.JsonCommonResource;
import yams.response.JsonResponse;
import yams.service.IApartmentService;
import yams.service.ICommonService;
import yams.service.IHouseService;
import yams.service.IUserService;
import yams.service.impl.DefaultCommonService;
import yams.utils.SystemTool;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 房屋对外接口实现类
 * Created by Silence on 2016/11/1.
 */
@SuppressWarnings("unchecked")
@RestController
@RequestMapping("/house")
public class DefaultHouseResource extends JsonCommonResource implements IHouseResource {

    private ICommonService skuService;
    private ICommonService bedService;
    private ICommonService dayPriceService;
    private ICommonService productService;

    @Resource
    private IApartmentService apartmentService;
    @Resource
    private IHouseService houseService;
    @Resource
    private IUserService userService;

    @RequestMapping(value = "/", method = RequestMethod.POST)
    @Override
    public JsonResponse<HouseEntity> page(@RequestBody HouseEntity houseEntity) {
        if (houseEntity.getName() != null)
            houseEntity.getProperties().put("name_like", houseEntity.getName());
        if (!StringUtils.isEmpty(houseEntity.getProperties().get("_cityId"))) {
            String cityId = houseEntity.getProperties().get("_cityId").toString();
            ApartmentEntity apartmentEntity = apartmentService.findById(cityId);
            List<ApartmentEntity> l = new ArrayList<>();
            l.addAll(apartmentEntity.getChildren());
            houseEntity.getProperties().put("apartment_in",l);
        }
        return _pageAll(houseService, houseEntity);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @Override
    public JsonResponse<HouseEntity> findById(@PathVariable String id) {

        JsonResponse<HouseEntity> result = _findOne(houseService, id, 0);
        HouseEntity house = result.getValue();
        UserEntity manage=userService.findById(house.getManager());
        if(house.getProperties() != null){
            house.getProperties().put("beds",house.findBeds());
            house.getProperties().put("dayPrices",house.findDayPrices());
            house.getProperties().put("manager",manage);
        }else{
            Map<String,Object> map = Maps.newConcurrentMap();
            map.put("beds",house.findBeds());
            map.put("dayPrices",house.findDayPrices());
            map.put("manager",manage);
            house.setProperties(map);
        }

        return result;

    }

    @RequestMapping(value = "/code/{code}", method = RequestMethod.GET)
    @Override
    public JsonResponse<HouseEntity> findByCode(@PathVariable String code) {
        return _findOne(houseService, code, 1);
    }

    @RequestMapping(value = "/", method = RequestMethod.PUT)
    @Override
    public JsonResponse<HouseEntity> save(@RequestBody HouseEntity houseEntity) {
        if(StringUtils.isEmpty(houseEntity.getCode()))
            houseEntity.setCode(System.currentTimeMillis()+"");
        return _saveInfo(houseService, houseEntity);

    }

    @RequestMapping(value = "/saveStatus", method = RequestMethod.PUT)
    public JsonResponse<HouseEntity> saveStatus(@RequestBody HouseEntity houseEntity) {
        HouseEntity result  = houseService.findById(houseEntity.getProperties().get("id").toString());
        result.setStatus(Integer.valueOf(houseEntity.getProperties().get("status").toString()));
        return _saveInfo(houseService, result);
    }

    /**
     * 保存床铺信息
     * @param houseEntity
     * @return
     */
    @RequestMapping(value = "/relation/", method = RequestMethod.PUT)
    @Override
    public JsonResponse<HouseEntity> saveRelation(@RequestBody HouseEntity houseEntity) {

        houseService.saveBeds(houseEntity);
        houseService.saveDayPrice(houseEntity);

        return JsonResponse.OK();

    }
    /**
     * 查找某房间的短租价格
     * @param houseId
     * @return
     */
    @RequestMapping(value = "/dayPrice/{houseId}", method = RequestMethod.GET)
    @Override
    public JsonResponse<DayPriceEntity> findHouseDayPriceById(@PathVariable String houseId) {

        DayPriceEntity dayPriceEntity = new DayPriceEntity();
        dayPriceEntity.getProperties().put("house_id_obj_ae",houseId);

        return _pageAll(dayPriceService, dayPriceEntity);

    }


    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @Override
    public JsonResponse<HouseEntity> delete(@PathVariable String id) {
        return _delete(houseService, id);
    }

    @Override
    public void initService() {

        if (skuService == null)
            skuService = new DefaultCommonService("skuRepository");
        if (bedService == null)
            bedService = new DefaultCommonService("bedRepository");
        if (dayPriceService == null)
            dayPriceService = new DefaultCommonService("dayPriceRepository");
        if (productService == null)
            productService = new DefaultCommonService("productRepository");
    }

    @RequestMapping(value = "/product/", method = RequestMethod.PUT)
    @Override
    public JsonResponse<HouseEntity> saveHouseProduct(@RequestBody HouseEntity house) {
        if (house.getProducts() != null) {
            HouseEntity o = (HouseEntity) houseService.findById(house.getId());
            Set<SkuEntity> set = new HashSet<>();
            house.getProducts().forEach(a -> {
                ProductEntity p = null;
                SkuEntity sku=new SkuEntity();
                if (a.getId() != null) {
                    p = (ProductEntity) productService.findById(a.getId());
                    if (p != null) {
                        sku.setId(SystemTool.uuid());
                        sku.setCode(p.getCode()+"-"+System.currentTimeMillis());
                        sku.setName(p.getName());
                        sku.setCreateBy(p.getCreateBy());
                        sku.setCreatedDate(p.getCreatedDate());
                        sku.setModifiedBy(house.getCreateBy());
                        sku.setModifiedDate(new Date());
                        sku.setHouse(house);
                        sku.setProduct(p);
                    }
                }
                set.add(sku);
            });
            skuService.getRepository().save(set);
        }
        return JsonResponse.OK();
    }

    @RequestMapping(value = "/cityHouse/", method = RequestMethod.POST)
    @Override
    public JsonResponse<HouseEntity> findHouseByCity(@RequestBody HouseEntity house) {
        ApartmentEntity apartmentEntity = new ApartmentEntity();
        apartmentEntity.setProperties(house.getProperties());
        List<ApartmentEntity> l = apartmentService.listAll(apartmentEntity);
        List<HouseEntity> ret = new ArrayList<>();
        l.forEach(a -> {
            ret.addAll(a.getHouses());
        });
        return JsonResponse.build(ret);
    }

    /**
     * 克隆房间功能
     * @param id
     * @return
     */
    @RequestMapping(value = "/clone/{id}", method = RequestMethod.GET)
    @Override
    public JsonResponse<HouseEntity> cloneHouse(@PathVariable String id) {
        HouseEntity houseEntity = (HouseEntity) houseService.findById(id);
        HouseEntity newHouse = new HouseEntity();
        newHouse.setAddress(houseEntity.getAddress());
        newHouse.setAImage(houseEntity.getAImage());
        newHouse.setBImage(houseEntity.getBImage());
        newHouse.setCImage(houseEntity.getCImage());
        newHouse.setDImage(houseEntity.getDImage());
        newHouse.setEImage(houseEntity.getEImage());
        newHouse.setFImage(houseEntity.getFImage());
        newHouse.setApartment(houseEntity.getApartment());
        newHouse.setArea(houseEntity.getArea());
        newHouse.setFloor(houseEntity.getFloor());
        newHouse.setHouseType(houseEntity.getHouseType());
        newHouse.setMonthly(houseEntity.getMonthly());
        newHouse.setPrimaryImage(houseEntity.getPrimaryImage());
        newHouse.setRecommend(houseEntity.getRecommend());
        newHouse.setShortDesc(houseEntity.getShortDesc());
        newHouse.setUedit(houseEntity.getUedit());
        newHouse.setName(houseEntity.getName());
        newHouse.setCode(houseEntity.getCode()+System.currentTimeMillis());
        newHouse.setRemark(houseEntity.getRemark());
        newHouse.setRowNum(houseEntity.getRowNum()+1);
        newHouse.setModifiedDate(new Date());
        newHouse.setCreatedDate(new Date());
        newHouse.setCreateBy("clone");
        newHouse.setModifiedBy("clone");
        return _saveInfo(houseService,newHouse);
    }

    /**
     * 修改房间所属房型
     * @param houseEntity
     * @return
     */
    @RequestMapping(value = "/houseGroup/update", method = RequestMethod.PUT)
    @Override
    public JsonResponse<HouseEntity> saveHouseGroup(@RequestBody HouseEntity houseEntity) {

        HouseEntity paramObj = houseService.findById(houseEntity.getId());
        paramObj.setHouseGroup(houseEntity.getHouseGroup());
        return _saveInfo(houseService,paramObj);

    }

    /**
     * 给某个房型添加一个或者一批房间
     * @param map
     * @return
     */
    @RequestMapping(value = "/houseGroup/add", method = RequestMethod.PUT)
    @Override
    public JsonResponse<HouseEntity> saveHouseGroup(@RequestBody Map<String,Object> map) {

        String houseGroup = (String)map.get("code");
        List<String> ids = (List<String>)map.get("ids");

        for(String id : ids){
            HouseEntity house = houseService.findById(id);
            house.setHouseGroup(houseGroup);
            houseService.getRepository().saveEntity(house);
        }

        return JsonResponse.OK();

    }

    /**
     * 移动端首页及长租房屋列表数据展现
     * @param houseEntity
     * @return
     */
    @RequestMapping(value = "/mobileIndex", method = RequestMethod.POST)
    @Override
    public JsonResponse<HouseEntity> mobileIndex(@RequestBody HouseEntity houseEntity) {

        houseEntity.getProperties().put("status","1");
        houseEntity.getProperties().put("monthRentAble",true);
        List<HouseEntity> houseList = houseService.listAll(houseEntity);

        Map<String,String> map = Maps.newConcurrentMap();
        List<HouseEntity> resultList = houseList.stream().filter(house -> {
            //每个房型组显示一间房，特殊情况，ROOM10的全显示
            if(StringUtils.isEmpty(map.get(house.getHouseGroup())) || house.getHouseGroup().equalsIgnoreCase("ROOM10")){
                map.put(house.getHouseGroup(),"Y");
                return true;
            }else{
                return false;
            }
        }).collect(Collectors.toList());

        return JsonResponse.build(resultList);

    }

    /**
     * 推荐房源
     * @param houseEntity
     * @return
     */
    @RequestMapping(value = "/mobileIndexRecommend", method = RequestMethod.POST)
    @Override
    public JsonResponse<HouseEntity> mobileIndexRecommend(@RequestBody HouseEntity houseEntity) {

        houseEntity.getProperties().put("status","1");
        houseEntity.getProperties().put("monthRentAble",true);
        List<HouseEntity> houseList = houseService.listAll(houseEntity);

        Map<String,String> map = Maps.newConcurrentMap();
        List<HouseEntity> resultList = houseList.stream().filter(house -> {
            //每个房型组显示一间房，特殊情况，ROOM10的全显示
            if((StringUtils.isEmpty(map.get(house.getHouseGroup())) &&  house.getRecommend() )|| house.getHouseGroup().equalsIgnoreCase("ROOM10")){
                map.put(house.getHouseGroup(),"Y");
                return true;
            }else{
                return false;
            }
        }).collect(Collectors.toList());

        return JsonResponse.build(resultList);

    }

    /**
     * 移动端短租房屋列表数据展现
     * @param houseEntity
     * @return
     */
    @RequestMapping(value = "/mobileShortList", method = RequestMethod.POST)
    @Override
    public JsonResponse<HouseEntity> mobileShortList(@RequestBody HouseEntity houseEntity) {

        houseEntity.getProperties().put("status","1");
        houseEntity.getProperties().put("dayRentAble",true);
        List<HouseEntity> houseList = houseService.listAll(houseEntity);

        Map<String,String> map = Maps.newConcurrentMap();
        List<HouseEntity> resultList = houseList.stream().filter(house -> {
            if(StringUtils.isEmpty(map.get(house.getHouseGroup()))){
                map.put(house.getHouseGroup(),"Y");
                return true;
            }else{
                return false;
            }
        }).collect(Collectors.toList());

        return JsonResponse.build(resultList);

    }

    /**
     * 点击某个长租房型，随机指定一间具体房屋
     * @param houseGroup
     * @param apartmentCity
     * @return
     */
    @RequestMapping(value = "/randomMonth", method = RequestMethod.GET)
    @Override
    public JsonResponse<HouseEntity> randomMonth(@RequestParam String houseGroup,@RequestParam String apartmentCity) {

        HouseEntity houseCondition = new HouseEntity();
        houseCondition.getProperties().put("status","1");
        houseCondition.getProperties().put("monthRentAble",true);
        houseCondition.getProperties().put("houseGroup",houseGroup);
        if(!StringUtils.isEmpty(apartmentCity) && !Objects.equals(apartmentCity,"undefined")){
            houseCondition.getProperties().put("apartment_city_obj_ae",apartmentCity);
        }
        List<HouseEntity> houseList = houseService.listAll(houseCondition);
        for (HouseEntity houseEntity:houseList){
            houseEntity.getProperties().put("manager",userService.findById(houseEntity.getManager()));
        }

        HouseEntity house = new HouseEntity();
        if(!CollectionUtils.isEmpty(houseList)){
            house = houseList.get(0);
        }

        return JsonResponse.buildSingle(house);

    }

    /**
     * 点击某个短租房型，随机指定一间具体房屋
     * @param houseType
     * @param apartmentCity
     * @return
     */
    @RequestMapping(value = "/randomDay", method = RequestMethod.GET)
    @Override
    public JsonResponse<HouseEntity> randomDay(@RequestParam String houseType,@RequestParam String apartmentCity) {

        HouseEntity houseCondition = new HouseEntity();
        houseCondition.getProperties().put("status","1");
        houseCondition.getProperties().put("dayRentAble",true);
        houseCondition.getProperties().put("houseType",houseType);
        if(!StringUtils.isEmpty(apartmentCity) && !Objects.equals(apartmentCity,"undefined")){
            houseCondition.getProperties().put("apartment_city_obj_ae",apartmentCity);
        }
        List<HouseEntity> houseList = houseService.listAll(houseCondition);

        HouseEntity house = new HouseEntity();
        if(!CollectionUtils.isEmpty(houseList)){
            house = houseList.get(0);
        }

        return JsonResponse.buildSingle(house);

    }
}
